import {useRef, useState} from "react";
import {useTheme} from "../../context/ThemeContext.tsx";
import * as chatController from "../../api/chatController";
import {Button, Input, Space, Spin, Tag, Upload} from "antd";
import {PaperClipOutlined, SendOutlined, UploadOutlined} from "@ant-design/icons";
import type {RcFile, UploadFile, UploadProps} from "antd/es/upload/interface";

interface AiSenderProps {
    conversationId: string;
    setConversationId: (s: string) => void;
    conversation: API.ConversationVO;
    setConversation: (c: API.ConversationVO) => void;
    uploadedFiles?: string[];
    onFilesChange?: (files: string[]) => void;
}


interface UploadChangeInfo {
    file: UploadFile & {
        originFileObj?: RcFile;
    };
    fileList: UploadFile[];
    event?: any;
}

export const AiSender = (props: AiSenderProps) => {
    const [value, setValue] = useState<string>("");
    const [loading, setLoading] = useState<boolean>(false);
    const {theme: currentTheme} = useTheme();
    const isInk = currentTheme === 'ink';
    const {uploadedFiles = [], onFilesChange} = props;
    const {conversationId, conversation, setConversation} = props;

    // 使用ref来跟踪是否已经发送了请求，避免重复发送
    const messageSentRef = useRef<boolean>(false);
    // 保存当前消息内容的引用，避免闭包问题
    const currentMessageRef = useRef<string>("");
    // 引用Input组件
    const inputRef = useRef<any>(null);

    // 处理发送消息
    const handleSendMessage = async () => {
        // 如果已经发送过或没有内容，则不再发送
        if (messageSentRef.current || !currentMessageRef.current.trim()) {
            return;
        }

        messageSentRef.current = true;
        setLoading(true);

        try {
            // 构建新的消息
            const newUserMessage: API.MessageWrapper = {
                type: "USER",
                content: currentMessageRef.current
            };

            // 先显示用户消息和"思考中"的助手消息
            const initialAssistantMessage: API.MessageWrapper = {
                type: "ASSISTANT",
                content: "思考中..."
            };

            // 先更新UI显示用户消息和思考中
            setConversation({
                ...conversation,
                messages: [
                    ...(conversation.messages || []),
                    newUserMessage,
                    initialAssistantMessage
                ]
            });

            // 调用新的聊天API，支持文件
            const response = await chatController.chat({
                conversationId: conversationId,
                message: currentMessageRef.current,
                files: uploadedFiles
            });

            if (response && Array.isArray(response)) {
                // API返回的响应内容
                const assistantResponse = response.join('\n');

                // 创建最终的助手消息对象
                const finalAssistantMessage: API.MessageWrapper = {
                    type: "ASSISTANT",
                    content: assistantResponse
                };

                // 直接更新最终的对话状态
                setConversation({
                    ...conversation,
                    messages: [
                        ...(conversation.messages || []),
                        newUserMessage,
                        finalAssistantMessage
                    ]
                });
            }

            setValue("");
        } catch (error) {
            console.error("Chat API error:", error);
        } finally {
            setLoading(false);
            messageSentRef.current = false;
        }
    };

    // 按下回车键发送消息
    const handleKeyPress = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            currentMessageRef.current = value;
            handleSendMessage();
        }
    };

    // 处理文件上传
    const handleFileUpload: UploadProps['customRequest'] = (options) => {
        if (options.onSuccess) {
            setTimeout(() => {
                options.onSuccess!("ok");
            }, 0);
        }
    };

    const handleUploadChange = (info: UploadChangeInfo) => {
        if (info.file.status === "done") {
            if (info.file.originFileObj) {
                onFilesChange?.([...(uploadedFiles || []), info.file.name]);
            }
        }
    };

    return (
        <div>
            {uploadedFiles && uploadedFiles.length > 0 && (
                <Space style={{marginBottom: '8px'}}>
                    <PaperClipOutlined/>
                    <span>已上传文件:</span>
                    {uploadedFiles.map((file, index) => (
                        <Tag
                            key={index}
                            color={isInk ? "blue" : "volcano"}
                            style={{
                                borderRadius: isInk ? '4px' : '12px',
                                fontFamily: 'var(--font-family)',
                            }}
                            className="file-tag-appear transition-all"
                        >
                            {file}
                        </Tag>
                    ))}
                </Space>
            )}
            <div
                style={{
                    display: "flex",
                    gap: "8px",
                    marginBottom: "24px",
                    alignItems: "flex-end",
                }}
            >
                <Upload
                    customRequest={handleFileUpload}
                    showUploadList={false}
                    onChange={handleUploadChange}
                >
                    <Button
                        type="default"
                        icon={<UploadOutlined/>}
                        style={{
                            height: "38px",
                            borderRadius: isInk ? "4px" : "16px",
                            fontFamily: 'var(--font-family)',
                        }}
                        className="transition-all"
                    />
                </Upload>
                <Input.TextArea
                    ref={inputRef}
                    value={value}
                    onChange={(e: React.ChangeEvent<HTMLTextAreaElement>) => setValue(e.target.value)}
                    onKeyPress={handleKeyPress}
                    style={{
                        flex: 1,
                        borderRadius: isInk ? "4px" : "16px",
                        borderColor: isInk ? "#d9d9d9" : "var(--cartoon-border-color)",
                        padding: "8px 12px",
                        resize: "none",
                        fontFamily: 'var(--font-family)',
                        transition: 'all 0.3s'
                    }}
                    placeholder={loading ? "思考中..." : (isInk ? "请输入..." : "有什么想问的...")}
                    className="styled-input input-focus-animation"
                    autoSize={{minRows: 1, maxRows: 6}}
                    disabled={loading}
                />
                <Button
                    type="primary"
                    onClick={() => {
                        currentMessageRef.current = value;
                        handleSendMessage();
                    }}
                    style={{
                        height: "38px",
                        borderRadius: isInk ? "4px" : "16px",
                        fontFamily: 'var(--font-family)',
                        background: isInk ? "#1677ff" : "var(--cartoon-gradient)",
                        border: "none"
                    }}
                    className="animated-button ripple-button"
                    disabled={!conversationId || loading}
                    loading={loading}
                    icon={<SendOutlined/>}
                >
                    发送
                </Button>
            </div>
            {loading && (
                <div style={{
                    textAlign: 'center',
                    marginTop: '8px'
                }}>
                    <Spin size="small"/>
                    <span style={{
                        marginLeft: '8px',
                        color: 'rgba(0, 0, 0, 0.45)',
                        fontFamily: 'var(--font-family)'
                    }} className="thinking-dots">
                        思考中
                    </span>
                </div>
            )}
        </div>
    );
};
